<div id='mosaicdiv'>Loading friends... Please wait.</div>
<script type='text/javascript'>
// This sample demonstrates pagination (progressive loading) of the 
// friends list by making several small OpenSocial requests

var first = 0;
var PAGE_SIZE = 20;
var friends = [];

// Makes the OpenSocial request to fetch friends from indices
// [first .. first + PAGE_SIZE - 1]
function startFetchPage() {
   var req = opensocial.newDataRequest();
   var param = {};

   // indicate the start index and how many friends we want to list
   param[opensocial.DataRequest.PeopleRequestFields.FIRST] = first;
   param[opensocial.DataRequest.PeopleRequestFields.MAX] = PAGE_SIZE;
   param[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
      opensocial.Person.Field.THUMBNAIL_URL
   ];

   var idspec = opensocial.newIdSpec({ "userId" : "VIEWER", 
       "groupId" : "FRIENDS" });
   req.add(req.newFetchPeopleRequest(idspec, param), "data");
   req.send(onLoadPage);
   debug.say("Loading friends " + first + " to " + (first + PAGE_SIZE) + "...");
}

// Called after all friends have been loaded -- builds the mosaic with
// everyone's photo
function buildMosaic() {
   var html = [];
   for (var i in friends) {
      html.push("<img src='");
      html.push(friends[i].getField(opensocial.Person.Field.THUMBNAIL_URL));
      html.push("' alt='");
      html.push(gadgets.util.escapeString(friends[i].getDisplayName()));
      html.push("'>");
   }
   document.getElementById('mosaicdiv').innerHTML = html.join('');
}

// Callback called by framework when each friends page is done loading
function onLoadPage(data) {
   if (data.hadError()) {
      debug.say("*** Error.");
      // handle error here
      return;
   }

   var returnedArray = data.get("data").getData().asArray();

   if (returnedArray.length == 0) {
      // done loading! No more friends to load.
      debug.say("Done loading. " + friends.length + " friends loaded.");
      buildMosaic();
   }
   else {
      // add to our current list
      friends = friends.concat(returnedArray);

      // and ask for the next page
      first += PAGE_SIZE;
      startFetchPage();
   }
}

gadgets.util.registerOnLoadHandler(startFetchPage);
</script>

